package com.tian.service.impl;

import com.tian.constant.RabbitMQConstant;
import com.tian.entity.RetryMessage;
import com.tian.enums.PayRetryMessageTypeEnum;
import com.tian.mapper.RetryMessageMapper;
import com.tian.producer.MessageRetrySendProducer;
import com.tian.service.UserUseCouponExchangeCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * {@code @description:} TODO
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-11-09 15:43
 * {@code @version:} 1.0
 */
@Slf4j
@Service
public class UserUseCouponExchangeCodeServiceImpl implements UserUseCouponExchangeCodeService {

    @Resource
    private RetryMessageMapper retryMessageMapper;
    @Resource
    private MessageRetrySendProducer messageRetrySendProducer;

    @Override
    public void process() {
        int count = retryMessageMapper.countRetryMessage(PayRetryMessageTypeEnum.COUPON_EXCHANGE_CODE_USED.getType(), 0);
        if (count == 0) {
            log.info("执行结束 userUseCouponExchangeCodeService 没有消息需要重发");
            return;
        }
        List<RetryMessage> retryMessages = retryMessageMapper.selectRetryMessage(PayRetryMessageTypeEnum.COUPON_EXCHANGE_CODE_USED.getType(), 0);
        for (RetryMessage retryMessage : retryMessages) {
            if (retryMessage.getRetriedTimes() > retryMessage.getRetry()) {
                // 已经超过最大重试次数的消息,发告警通知到相关人员
                // TODO 告警通知
                log.info("执行结束 userUseCouponExchangeCodeService 重发次数达到上限，消息id为 {}", retryMessage.getId());
                continue;
            }
            messageRetrySendProducer.sendMessage(retryMessage, RabbitMQConstant.USER_USE_COUPON_EXCHANGE_CODE_EXCHANGE, RabbitMQConstant.USER_USE_COUPON_EXCHANGE_CODE_ROUTING_KEY);
        }
        log.info("执行结束 userUseCouponExchangeCodeService 处理了 {} 条消息", count);
    }
}
